package cn.itcast.bos.web.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.utils.BaseAction;
import cn.itcast.bos.service.base.AreaService;
import cn.itcast.bos.utils.PinYin4jUtils;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Actions
@Scope("prototype")
public class AreaAction extends BaseAction<Area> {

	// 接受上传文件
	private File file;

	public void setFile(File file) {
		this.file = file;
	}

	@Autowired
	private AreaService areaService;

	@Action(value = "areaImport")
	public void batchImport() throws IOException {
		List<Area> areas = new ArrayList<>();
		// 编写解析代码逻辑
		// 基于.xls格式解析HSSF
		// 1.加载excel文件对象
		HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));
		// 2.读取一个sheet
		HSSFSheet sheet = workbook.getSheetAt(0);
		// 3.读取sheet中的每一行
		for (Row row : sheet) {
			// 一行数据对象一个区域对象
			if (row.getRowNum() == 0) {
				// 第一行跳过
				continue;
			}
			if (row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
				// 空行跳过
				continue;
			}
			Area area = new Area();
			area.setId(row.getCell(0).getStringCellValue());
			area.setProvince(row.getCell(1).getStringCellValue());
			area.setCity(row.getCell(2).getStringCellValue());
			area.setDistrict(row.getCell(3).getStringCellValue());
			area.setPostcode(row.getCell(4).getStringCellValue());
			// 基于pinyin4j来生成城市编码和简码
			String province = area.getProvince();
			String city = area.getCity();
			String district = area.getDistrict();
			province = province.substring(0, province.length() - 1);
			city = city.substring(0, city.length() - 1);
			district = district.substring(0, district.length() - 1);
			// 简码
			String[] headByString = PinYin4jUtils.getHeadByString(province + city + district);
			StringBuffer buffer = new StringBuffer();
			for (String string : headByString) {
				buffer.append(string);
			}

			String string = buffer.toString();
			area.setShortcode(string);
			// 城市编码
			String pinyin = PinYin4jUtils.hanziToPinyin(city, "");
			area.setCitycode(pinyin);
			areas.add(area);
		}

		// 调用业务层
		areaService.save(areas);
	}

	/***
	 * 分页查询
	 */

	@Action(value = "area_findAll", results = { @Result(name = "success", type = "json") })
	public String findAll() {

		// 封装Pageable对象
		Pageable pageable = new PageRequest(page - 1, rows);
		// 封装条件查询对象
		Specification<Area> spec = new Specification<Area>() {
			/***
			 * root:用于获得属性字段 CriteriaQuery:可以用于简单条件查询 CriteriaBuilder:用于构造复杂条件查询
			 */
			@Override
			public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> pred = new ArrayList<Predicate>();
				// 判断条件是否为空

				if (StringUtils.isNotBlank(model.getProvince())) {
					Predicate p2 = cb.like(root.get("province").as(String.class), "%" + model.getProvince() + "%");
					pred.add(p2);
				}

				if (StringUtils.isNotBlank(model.getCity())) {
					Predicate p1 = cb.like(root.get("city").as(String.class), "%" + model.getCity() + "%");
					pred.add(p1);
				}

				if (StringUtils.isNotBlank(model.getDistrict())) {
					Predicate p3 = cb.like(root.get("district").as(String.class), "%" + model.getDistrict() + "%");
					pred.add(p3);
				}

				return cb.and(pred.toArray(new Predicate[0]));
			}
		};
		Page<Area> cour = areaService.findAll(spec, pageable);
		pushPageDataToValueStack(cour);
		return SUCCESS;
	}

	/***
	 * 增加
	 */
	@Action(value = "area_save", results = {
			@Result(name = "success", type = "redirect", location = "/pages/base/area.html") })
	public String area_save() {
		model.setId(model.getCitycode());
		areaService.saveArea(model);

		return SUCCESS;
	}

	/***
	 * 删除
	 */
	private String ids;

	public void setIds(String ids) {
		this.ids = ids;
	}

	@Action(value = "area_delBatch", results = {
			@Result(name = "success", type = "redirect", location = "/pages/base/area.html") })
	public String area_del() {
		 String[] id = ids.split(",");
		areaService.delBacth(id);

		return SUCCESS;
	}

}
